function $(id){
	return document.getElementById(id);
}
window.requestAnimationFrame = (function(){
    return  window.requestAnimationFrame       ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame    ||
            window.oRequestAnimationFrame      ||
            window.msRequestAnimationFrame     ||
            function (callback) {
                window.setTimeout(callback, 1000 / 60);
            };
})();
window.cancelAnimationFrame = ( function() {
    return window.cancelAnimationFrame ||
        window.webkitCancelRequestAnimationFrame ||
        window.mozCancelRequestAnimationFrame ||
        window.oCancelRequestAnimationFrame ||
        window.msCancelRequestAnimationFrame ||
        clearTimeout;
} )();
var map = [
	[3,1,1,1,1,1,1,1,1,1],
	[1,1,1,1,1,1,1,1,1,1],
	[1,1,1,1,1,1,1,1,1,1],
	[1,1,1,1,1,1,1,1,1,1],
	[1,1,1,1,1,1,1,1,1,1],
	[1,1,1,1,1,1,1,1,1,1],
	[1,1,1,1,1,1,1,1,1,1],
	[1,1,1,1,1,1,1,1,1,1],
	[1,1,1,1,1,1,1,1,1,1],
	[1,1,1,1,1,1,1,1,1,1]
];
var w, h, bg, canvas, ctx1, ctx2;
var direction = 0;//控制方向
var flag = true;
var id = null;		//动画执行句柄
var id1 = null;		//动画队列句柄
var id2 = null;		//动画队列句柄
var ready = 'yes';	//是否可执行下一个动画
w = $('wrap').offsetWidth;
h = $('wrap').offsetHeight;
bg = $('bg');
bg.width = w;
bg.height = h;
canvas = $('canvas');
canvas.width = canvas.height = 50;
canvas.style.top = '50px';
canvas.style.left = '50px';
ctx1 = bg.getContext('2d');
ctx2 = canvas.getContext('2d');

/*初始化背景*/
function initBg(){
	for(var i = 1; i <= 11; i++){
		ctx1.fillText(i, 25, 50*i+25);
		ctx1.fillText(i, 50*i+25, 25);
		ctx1.beginPath();
		ctx1.moveTo(50, 50*i);
		ctx1.lineTo(550, 50*i);
		ctx1.stroke();
		ctx1.beginPath();
		ctx1.moveTo(50*i, 50);
		ctx1.lineTo(50*i, 550);
		ctx1.stroke();
	}
}
initBg();

/*初始化小方块*/
function draw(){
	var bg = ctx2.createLinearGradient(0,0,0,50);
	bg.addColorStop(0, 'blue');
	bg.addColorStop(0.2, 'blue');
	bg.addColorStop(0.2, 'red');
	bg.addColorStop(1, 'red');
	ctx2.fillStyle = bg;
	ctx2.fillRect(0,0,50,50);
}
draw();
/*获得当前的角度*/
function getAngle(){

	var a = canvas.style.transform.match(/\((\d+)deg/);
	if(a == null)
		a = 0;
	else
		a = +a[1];
	return a;
}

/*旋转*/
function rotate( angle, target){
	if(target == undefined){
		target = Math.abs(angle);
		angle = angle > 0 ? 1 : -1;
	}
	if(target > 0){
		var a = getAngle() + angle;
		canvas.style.transform = 'rotate('+ a +'deg)';
		target -=1;
		id = requestAnimationFrame(function(){
			rotate(angle, target);
		});
		ready = 'no';
	}else{
		cancelAnimationFrame(id);
		ready = 'yes';
	}
}

/*前进*/
function go(number, target, origin){
	var top = parseInt(canvas.style.top);
	var left = parseInt(canvas.style.left);
	if(target == undefined)
		target = 50;
	switch(number){
		case 0:
			if(top > 50 && target > 0 && map[Math.ceil((top < 50 ? 51 : top)/50)-2][Math.floor(left/50)-1] != 0){
				canvas.style.top = top-1 + 'px';
				target -= 1;
				id = requestAnimationFrame(function(){
					if(((Math.abs(top) - origin)/50+'').indexOf('.') == -1){
						if((Math.floor(top)/50) >= 0 && Math.floor(top/50) <=9)
							map[Math.floor(parseInt(canvas.style.top)/50)][Math.floor(parseInt(canvas.style.left)/50)-1] = 1;
						origin = parseInt(canvas.style.top);
					}
					go(number, target, origin);
				});
				ready = 'no';
			}else{
				cancelAnimationFrame(id);
				map[Math.floor(parseInt(canvas.style.top)/50)-1][Math.floor(parseInt(canvas.style.left)/50)-1] = 3;
				ready = 'yes';
			}
			break;
		case 1:
			if(left < 500 && target > 0 && map[Math.floor(parseInt(canvas.style.top)/50)-1][Math.floor((left > 500 ? 500:left)/50)] != 0){
				canvas.style.left = left+1 + 'px';
				target -= 1;
				id = requestAnimationFrame(function(){
					if((Math.abs(parseInt(canvas.style.left) - origin)/50+'').indexOf('.') == -1){
						if(Math.floor(parseInt(canvas.style.left)/50)-2 >= 0 && Math.floor(parseInt(canvas.style.left)/50)-2 <=9)
							map[Math.floor(parseInt(canvas.style.top)/50)-1][Math.floor(parseInt(canvas.style.left)/50)-2] = 1;
						origin = parseInt(canvas.style.left);
						console.log(map[0][0], map[0][1], map[0][2], map[0][3]);
					}
					go(number, target, origin);
				});
				ready = 'no';
			}else{
				cancelAnimationFrame(id);
				map[Math.floor(parseInt(canvas.style.top)/50)-1][Math.floor(parseInt(canvas.style.left)/50)-1] = 3;
				ready = 'yes';
			}
			break;
		case 2:
			if(top < 500 && target > 0 && map[Math.floor((top > 500 ? 500 : top)/50)][Math.floor(parseInt(canvas.style.left)/50)-1] != 0){
				canvas.style.top = top+1 + 'px';
				target -= 1;
				id = requestAnimationFrame(function(){
					if((Math.abs(parseInt(canvas.style.top) - origin)/50+'').indexOf('.') == -1){
						if(Math.floor(parseInt(canvas.style.top)/50)-2 >= 0 && Math.floor(parseInt(canvas.style.top)/50)-2 <=9)
							map[Math.floor(parseInt(canvas.style.top)/50)-2][Math.floor(parseInt(canvas.style.left)/50)-1] = 1;
						origin = parseInt(canvas.style.top);
					}
					go(number, target, origin);
				});
				ready = 'no';
			}else{
				cancelAnimationFrame(id);
				map[Math.floor(parseInt(canvas.style.top)/50)-1][Math.floor(parseInt(canvas.style.left)/50)-1] = 3;
				ready = 'yes';
			}
			break;
		case 3:
			if(left > 50 && target > 0 && map[Math.floor(parseInt(canvas.style.top)/50)-1][Math.ceil((left < 50 ? 51 : left)/50)-2] != 0){
				canvas.style.left = left-1 + 'px';
				target -= 1;
				id = requestAnimationFrame(function(){
					if((Math.abs(parseInt(canvas.style.left) - origin)/50+'').indexOf('.') == -1){
						if(Math.floor(parseInt(canvas.style.left)/50) >= 0 && Math.floor(parseInt(canvas.style.left)/50) <=9)
							map[Math.floor(parseInt(canvas.style.top)/50)-1][Math.floor(parseInt(canvas.style.left)/50)] = 1;
						origin = parseInt(canvas.style.left);

					}
					go(number, target, origin);
				});
				ready = 'no';
			}else{
				cancelAnimationFrame(id);
				map[Math.floor(parseInt(canvas.style.top)/50)-1][Math.floor(parseInt(canvas.style.left)/50)-1] = 3;
				ready = 'yes';
			}
			break;
	}
}
/*检测输入是否合法并添加行*/
$('tex').onkeyup = function(e){
	var e = e || window.event;
	var a = this.value;

	var value = this.value.split('\n');
	if(!value[value.length-1])
		value.length -=1;
	if(e.keyCode === 13){
		var span = document.createElement('span');
		span.innerHTML = parseInt($('row').lastElementChild.innerHTML) + 1;
		$('row').appendChild(span);
	}
	for(var i = 0; i < value.length; i++){
		var temp = value[i].trim();
		if(/^bru/.test(value[i]))
			temp = value[i].match(/(bru)\s+(.+)/);
		else
			temp = value[i].match(/([a-zA-Z]+\s*[a-zA-Z]*)\s*([^,]*)?,?(.*)?/);
		if(temp && temp[1])
			temp[1] = temp[1].trim();
		var reg = /^bru\s*.*|^build$|^go$|^tun\slef$|^tun\srig$|^tun\sbac$|^tra\slef$|^tra\stop$|^tra\srig$|^tra\sbot$|^mov\slef$|^mov\stop$|^mov\srig$|^mov\sbot$|^mov\sto$/i;
		if(!temp){
			$('row').children[i].style.background = '#f00';
			flag = true;
		}
		else if(temp[1] && !temp[2]){
			if(reg.test(temp[1])){
				$('row').children[i].style.background = '#ccc';
				flag = false;
			}else{
				$('row').children[i].style.background = '#f00';
				flag = true;
			}
		}else if(temp[2] && !temp[3]){
			if(temp[1].trim().toLowerCase() == 'bru'){
				$('row').children[i].style.background = '#ccc';
				flag = false;
			}
			else if(/[^\d+]/.test(temp[2]) || temp[1].trim().indexOf(' ') == -1 && /[^\d+]/.test(temp[2])){
				$('row').children[i].style.background = '#f00';
				flag = true;
			}else{
				$('row').children[i].style.background = '#ccc';
				flag = false;
			}
		}else if(temp[3]){
			if(/[^\d+]/.test(temp[3])){
				$('row').children[i].style.background = '#f00';
				flag = true;
			}else if(temp[3] > 10 || temp[3] <= 0 || temp[2] > 10 || temp[2] <= 0){
				$('row').children[i].style.background = '#f00';
				flag = true;
			}
			else{
				$('row').children[i].style.background = '#ccc';
				flag = false;
			}
		}
		else{
			$('row').children[i].style.background = '#f00';
			flag = true;
		}
	}
};
/*textarea滚动条时间联动左边的行数*/
$('tex').onscroll = function(){
	$('row').scrollTop = this.scrollTop;
};

/*清除按钮*/
$('refresh').onclick = function(){
	$('tex').value = '';
	$('row').innerHTML = '<span>1</span>';
};



$('btn').onclick = main;
function main(e, path){
	if(flag){
		alert('请把命令填写正确');
		return;
	}
	var value, temp1 = [];
	var count = 1;
	var command = '';
	value = $('tex').value.trim().split('\n');
	
	if(!value[value.length - 1]){
		value.length -= 1; 
	}
	for(var j = 0; j < value.length; j++){
		var temp = value[j].trim().split(' ');
		
		if(temp.length == 1){
			temp1.push([temp[0].toLowerCase(),1]);
		}else if(temp.length == 2){
			if(/bru/.test(temp[0])){
				temp1.push([temp[0].toLowerCase().trim(), temp[1]]);
			}
			else if(/\d+/.test(temp[1])){
				temp1.push([temp[0].toLowerCase(),temp[1]]);
			}else{
				temp1.push([temp[0].toLowerCase() + ' ' + temp[1].toLowerCase(),1]);
			}
		}else if(temp.length == 3){
			if(temp[0].trim().toLowerCase() + temp[1].trim().toLowerCase() == 'movto'){
				var x = +temp[2].split(',')[0] - 1;
				var y = +temp[2].split(',')[1] - 1;
				map[x][y] = 4;
				var a = commandLine();
				for(var i in a){
					animation(a[i], 1);
				}
				if(x == (parseInt(canvas.style.top)/50-1) && y == (parseInt(canvas.style.left)/50-1)){
					continue;
				}
				map[x][y] = 3;
			}else{
				temp1.push([temp[0].toLowerCase() + ' ' + temp[1].toLowerCase(),temp[2]]);	
			}	
		}
	}
	console.log(temp1);
	for(var i in temp1){
		animation(temp1[i][0], temp1[i][1]);
	}
};